import { Config } from "./src/config/Config";
import { RedisConfig } from "./src/config/RedisConfig";
import { Logger } from "./src/engine/utils/Logger";
import { RedisClient } from "./src/engine/utils/RedisClient";
import { RedisManager } from "./src/engine/utils/RedisManager";
import { WebReqHandler } from "./src/engine/webserver/WebReqHandler";
import { ZoneModel } from "./src/model/ZoneModel";
import { IpUtil } from "./src/engine/utils/IpUtil";

const fs = require("fs")
const path = require("path")
const express = require("express");
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
const http = require("http");

export class WebServer {
    public static instance: WebServer = new WebServer();

    public init() {
        Config.serverType = Config.ServerType_List.WebServer;
        Logger.tag = Config.ServerType_List.WebServer;
        IpUtil.loadFile(path.resolve()+"/ip.txt")
        // ZoneModel.init();
        // RedisManager.instance.init();
        for (let i = 0; i < Config.WebPortList.length; i++) {
            let app = express();
            let publicPath = path.resolve() + "/public" + Config.WebPortList[i];
            if (!fs.existsSync(publicPath)) {
                fs.mkdirSync(publicPath);
            }
            app.use(bodyParser.urlencoded({ extended: false })); //解析post请求数据
            app.use(bodyParser.text()); // for parsing application/json
            app.use(bodyParser.json()); // for parsing application/json
            //设置静态网页目录
            let options = {
                setHeaders: function (res, path, stat) {
                    res.set('Access-Control-Allow-Origin', '*')
                }
            }
            app.use(express.static(publicPath, options));
            app.use(cookieParser())
            app.all('*', function (req, res, next) {
                req.header("Content-Type", "application/json;charset=UTF-8");
                res.header("Access-Control-Allow-Origin", "*");//项目上线后改成页面的地址
                res.header("Content-Type", "application/json;charset=UTF-8");
                res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
                next();
            });
            WebReqHandler.instance.init(app);
            http.createServer(app).listen(Config.WebPortList[i]);
            Logger.info("startWebServer suc=", Config.WebPortList[i]);
        }
    }

    public initServerList() {
        let redis: RedisClient = RedisManager.instance.getRedis(RedisConfig.Database_Index.Users);
        let str: string = JSON.stringify(ZoneModel.zoneModelList);
        // Logger.log("initServerLis==", ZoneModel.zoneModelList, str)
        redis.setValue(ZoneModel.Redis_Key, str);
    }
}

try {
    WebServer.instance.init();
    Logger.log("start suc====")
} catch (error) {
    Logger.error("WebMain.error=", error)
}
